import 'package:bloc/bloc.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test_demo/database/index.dart';
import 'package:flutter_test_demo/model/index.dart';
import 'package:flutter_test_demo/pages/shop_cart_bloc/view.dart';

import 'state.dart';

class HomeBlocCubit extends Cubit<HomeBlocState> {
  HomeBlocCubit() : super(HomeBlocState().init()) {
    getData();
  }

  void getData() async {
    // state.goodsList = await MethodDao.queryGoodsList();
    // print("HomePageLogic--:${state.goodsList.length}");
    // if(state.goodsList.isEmpty){
    //   await SqliteDataManger.getInstance().initData();
    //   state.goodsList = await MethodDao.queryGoodsList();
    // }
    // emit(state.clone()..goodsList = state.goodsList);
    List<GoodsListModel> goodsList = await MethodDao.queryGoodsList();
    if(goodsList.isEmpty){
      await SqliteDataManger.getInstance().initData();
      goodsList = await MethodDao.queryGoodsList();
    }
    emit(state.clone()..goodsList = goodsList);
  }

  void queryGoodsList() async {
    state.goodsList = await MethodDao.queryGoodsList();
    emit(state.clone());
  }

  void addCount(GoodsListModel model) {
    if(model.goodsQty != null) {
      model.goodsQty = model.goodsQty! + 1;
    }
    emit(state.clone());
  }

  void subCount(GoodsListModel model) async {
    if(model.goodsQty != null) {
      if(model.goodsQty! < 1) {
        return ;
      }
      model.goodsQty = model.goodsQty! - 1;
      if(model.goodsQty! == 0) {
        List<CartModel> cartGoodsList = await MethodDao.queryCartGoodsList();
        CartModel? data = cartGoodsList.firstWhereOrNull((item) => item.shopCartCode == model.goodsCode);
        if(data != null) {
          await MethodDao.deleteCartGoodsList(data);
        }
      }
    }
    emit(state.clone());
  }

  num totalPrice() {
    num total = 0;
    if(state.goodsList.isNotEmpty) {
      for (var e in state.goodsList) {
        if(e.goodsQty != null && e.goodsQty! > 0) {
          total = total + (e.goodsQty! * (e.goodsPrice ?? 0));
        }
      }
    }
    return total;
  }

  void addCart(BuildContext context) async {
    if(state.goodsList.isEmpty) {
      showDialog(title: '暂无商品', context: context);
      return ;
    }
    bool flag = state.goodsList.every((e) => e.goodsQty == 0);
    if(flag) {
      showDialog(title: '请选择商品', context: context);
      return ;
    }
    List<CartModel> cartGoodsList = await MethodDao.queryCartGoodsList();
    List<CartModel> cartList = [];

    for (var e in state.goodsList) {
      if(e.goodsQty != null && e.goodsQty! > 0) {
        CartModel m = CartModel();
        m.id = e.id;
        m.shopCartName = e.goodsName;
        m.shopCartCode = e.goodsCode;
        m.shopCartPrice = e.goodsPrice;
        m.shopCartQty = e.goodsQty;
        cartList.add(m);
      }
    }
    if(cartList.isNotEmpty) {
      for (var e in cartList) {
        CartModel? model = cartGoodsList.firstWhereOrNull((item) => item.shopCartCode == e.shopCartCode);
        if(model != null) {
          if(e.shopCartQty != model.shopCartQty) {
            await MethodDao.updateCartGoodsList(e);
          }
        } else {
          await MethodDao.insertCartGoodsList(e);
        }
      }
    }
    updateGoods();

    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const ShopCartBlocPage()),
    ).then((v) {
      queryGoodsList();
    });
  }

  void updateGoods() async {
    if(state.goodsList.isNotEmpty) {
      for (var e in state.goodsList) {
        await MethodDao.updateGoodsList(e);
      }
    }
  }

  void showDialog({required String title, required BuildContext context}) {
    showCupertinoDialog(
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          title: const Text(
            '提示',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            textAlign: TextAlign.center,
          ),
          content: Padding(
            padding: const EdgeInsets.only(top: 6),
            child: Text(title, style: const TextStyle(fontSize: 15), textAlign: TextAlign.center,),
          ),
          actions: [
            CupertinoDialogAction(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('确定'),
            ),
            CupertinoDialogAction(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
          ],
        );
      });

  }


}

extension IterableExtension<E> on Iterable<E> {
  E? firstWhereOrNull(bool Function(E) test) {
    for (final element in this) {
      if (test(element)) return element;
    }
    return null;
  }
}